<template>
  <el-upload v-model:file-list="fileList" action="/api/store/products/upload" list-type="picture-card"
    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="uploadSuccess">
    <el-icon>
      <Plus />
    </el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import type {
  UploadFile,
  UploadFiles,
  UploadProps,
  UploadUserFile
} from "element-plus";
const emit = defineEmits(["update:modelValue", "handleChange"]);
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: () => false
  }
});

const fileList = ref<UploadUserFile[]>([
  // {
  //   name: "food.jpeg",
  //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
  // },
  // {
  //   name: "food.jpeg",
  //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
  // }
]);

type ImageInfo = {
  name: string;
  url: string;
};

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
watch(
  () => props.modelValue,
  newValue => {
    const imageList = newValue.map(imageRaw => {
      const imageInfo = imageRaw as ImageInfo;
      if (imageInfo.url.indexOf("/_upload") !== -1) {
        return imageInfo;
      }
      return {
        url: `/_upload${imageInfo.url}`,
        name: imageInfo.name
      };
    });
    fileList.value = [...imageList] as any;
  },
  { immediate: true, deep: true }
);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  const urls = uploadFiles.map((file: UploadFile) => {
    if (file.response) {
      return {
        name: file.name,
        url: file.response.data.link
      };
    }
    return file;
  });
  emit("update:modelValue", urls);
};

const uploadSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  // console.log(response);
  // console.log(uploadFile);
  // console.log(uploadFiles);
  const urls = uploadFiles.map((file: UploadFile) => {
    if (file.response) {
      return {
        name: file.name,
        url: file.response.data.link
      };
    }
    return file;
  });
  emit("update:modelValue", urls);
};

const handlePictureCardPreview: UploadProps["onPreview"] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
</script>
